package com.ruoyi.common.utils;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class CSVUtils {

      /**写入csv文件
        * @param headers 列头
        * @param data 数据内容
        * @param filePath 创建的csv文件路径
        * @throws IOException *
      */

      private final static String NEW_LINE_SEPARATOR="\n";

      public static void writeCsv(String[] headers, List<String[]> data, String filePath) throws IOException {

                 //初始化csvformat
                 CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);

                 //创建FileWriter对象
                 FileWriter fileWriter=new FileWriter(filePath);

                 //创建CSVPrinter对象
                 CSVPrinter printer=new CSVPrinter(fileWriter,formator);

                 //写入列头数据
                 printer.printRecord((Object) headers);

                 if(null!=data){
                         //循环写入数据
                         for(String[] lineData:data){
                             printer.printRecord((Object) lineData);

                             }
                     }

                 System.out.println("CSV文件创建成功,文件路径:"+filePath);

             }
}
